package chessgame

import (
	"context"
	"gateway/client"
	"gateway/config/chessgame"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"log"
	"net/http"
	"time"
)

var conn, err = grpc.Dial(*client.ChessGameAddr, grpc.WithInsecure())
var c = chessgame.NewChessGameClient(conn)

func GetChessRoomList(userId int) (gin.H, error) {
	cxt, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	list, err := c.ShowGameList(cxt, &chessgame.ShowGameRoomListRequest{UserId: int32(userId)})
	if err != nil {

		return gin.H{"status": http.StatusBadRequest}, err
	}
	return gin.H{"status": http.StatusOK, "roomlist": list.RoomList}, err
}
func ShowCombatRecord(userId int, roomId int) (gin.H, error) {
	cxt, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	records, err := c.ViewGameBattleRecords(cxt, &chessgame.ViewBattleRecordsRequest{
		UserId: int32(userId),
		RoomId: int32(roomId),
	})

	if err != nil {

		return gin.H{"status": http.StatusBadRequest, "message": err.Error()}, err
	}
	if len(records.BattleRecords) == 0 {
		records.BattleRecords = nil
	}
	return gin.H{"status": records.Status, "combat_record": records.BattleRecords}, err
}
func CreateChessGameRoom(roomId int, playerAId int, isPve bool) (gin.H, error) {
	cxt, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	room, err := c.CreateChessRoom(cxt, &chessgame.CreateRoomRequest{
		RoomId:    int32(roomId),
		PlayerAId: int32(playerAId),
		IsPve:     isPve,
	})
	if err != nil {

		return gin.H{"status": http.StatusBadRequest, "message": err.Error()}, err
	}
	return gin.H{"status": room.Status, "message": "成功创建", "data": room.Value}, err
}

func JoinRoom(roomId int, playerBId int) (gin.H, error) {
	cxt, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	room, err := c.JoinChessRoom(cxt, &chessgame.JoinRoomRequest{
		RoomId:    int32(roomId),
		PlayerBId: int32(playerBId),
	})
	if err != nil {
		return gin.H{"status": http.StatusBadRequest, "message": err.Error()}, err
	}
	log.Println(room.ChatRoomId2)

	return gin.H{"status": room.Status, "message": "加入成功", "data": room.Value, "chatRoomId": room.ChatRoomId2}, err
}

func PlayGame(roomId int, userId int, x int, y int, nickName string) (gin.H, error) {
	cxt, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	game, err := c.PlayChessGame(cxt, &chessgame.PlayGameRequest{
		RoomId:       int32(roomId),
		PlayerId:     int32(userId),
		CoordinatesX: int32(x),
		CoordinatesY: int32(y),
		NickName:     nickName,
	})
	if err != nil {
		return gin.H{"status": http.StatusBadRequest, "message": err.Error()}, err
	}
	if game.Winner != "" {

		return gin.H{"status": http.StatusOK, "Winner": game.Winner, "data": game.Value}, err
	} else {
		return gin.H{"status": http.StatusOK, "message": game.Value}, err
	}
}
